﻿using System.Collections;
using System.Drawing;
using System.Windows.Forms;

namespace ToolUtil
{
    public static class ListBoxTool
    {
        /// <summary>
        /// 修改comboBox中值高度
        /// </summary>
        /// <param name="list"></param>
        /// <param name="itemHeight"></param>
        public static void cmbBind(ComboBox list, int itemHeight)
        {
            list.DropDownStyle = ComboBoxStyle.DropDownList;
            list.ItemHeight = itemHeight;
            list.DrawMode = DrawMode.OwnerDrawFixed;

            list.DrawItem += new DrawItemEventHandler(delegate (object sender, DrawItemEventArgs e)
            {
                if (e.Index < 0)
                {
                    return;
                }
                e.DrawBackground();
                e.DrawFocusRectangle();
                e.Graphics.DrawString((list.Items[e.Index]).ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds.X+3, e.Bounds.Y + 6);
            });
        }
        public static void MoveSelectedItemUp(this ListBox listBox)
        {
            _MoveSelectedItem(listBox, -1);
        }

        public static void MoveSelectedItemDown(this ListBox listBox)
        {
            _MoveSelectedItem(listBox, 1);
        }

        static void _MoveSelectedItem(ListBox listBox, int direction)
        {
            // Checking selected item 
            if (listBox.SelectedItem == null || listBox.SelectedIndex < 0)
                return; // No selected item - nothing to do 

            // Calculate new index using move direction 
            int newIndex = listBox.SelectedIndex + direction;

            // Checking bounds of the range 
            if (newIndex < 0 || newIndex >= listBox.Items.Count)
                return; // Index out of range - nothing to do 

            object selected = listBox.SelectedItem;

            // Save checked state if it is applicable 
            var checkedListBox = listBox as CheckedListBox;
            var checkState = System.Windows.Forms.CheckState.Unchecked;
            if (checkedListBox != null)
                checkState = checkedListBox.GetItemCheckState(checkedListBox.SelectedIndex);

            // Removing removable element 
            listBox.Items.Remove(selected);
            // Insert it in new position 
            listBox.Items.Insert(newIndex, selected);
            // Restore selection 
            listBox.SetSelected(newIndex, true);

            // Restore checked state if it is applicable 
            if (checkedListBox != null)
                checkedListBox.SetItemCheckState(newIndex, checkState);
        }
    }
}
